package com.xjnt.frameworks.plugin.sql.criterion.expression;

import com.jfinal.plugin.activerecord.ActiveRecordException;
import com.xjnt.frameworks.plugin.sql.consts.KeyWord;
import com.xjnt.frameworks.plugin.sql.criterion.Criterion;
import com.xjnt.frameworks.plugin.sql.criterion.SqlCriteria;
import com.xjnt.frameworks.plugin.sql.criterion.SqlType;
import com.xjnt.frameworks.plugin.sql.criterion.TypedValue;

public class BetweenExpression implements Criterion {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private String columnName;
	private Object lo;
	private Object hi;

	public BetweenExpression(String columnName, Object lo, Object hi) {
		this.columnName = columnName;
		this.lo = lo;
		this.hi = hi;
	}

	@Override
	public String toSql(SqlCriteria criteria) {
		StringBuilder sql = new StringBuilder();
		if (criteria.isExists(columnName)) {
			sql.append(columnName);
			sql.append(" ");
			sql.append(KeyWord.BETWEEN.getValue());
			sql.append(" ");
			sql.append("?");
			sql.append(" ");
			sql.append(KeyWord.AND.getValue());
			sql.append(" ");
			sql.append("?");
			return sql.toString();
		} else {
			throw new ActiveRecordException("The " + columnName + " is not exists ");
		}
	}

	@Override
	public TypedValue[] getTypedValues(SqlCriteria criterion) {
		return new TypedValue[] {
				new SqlType().getTypedValue(criterion, columnName, lo),
				new SqlType().getTypedValue(criterion, columnName, hi) };
	}

	public String getColumnName() {
		return columnName;
	}

	public Object getLo() {
		return lo;
	}

	public Object getHi() {
		return hi;
	}
}
